/**
 * 
 */
package huajiu.com.utlis;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Encoder;

/**
 * @author ItBotPjq
 *2018年1月24日
 */
public class ImageUtil {
	
	/**
	 * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	 * @param imgFilePath
	 * @return
	 */
	 public static String getImageStr(String imgFilePath) {
		    byte[] data = null;
		     
		    // 读取图片字节数组
		    try {
		      InputStream in = new FileInputStream(imgFilePath);
		      data = new byte[in.available()];
		      in.read(data);
		      in.close();
		    } catch (IOException e) {
		      e.printStackTrace();
		    }
		     
		    // 对字节数组Base64编码
		    BASE64Encoder encoder = new BASE64Encoder();
		    return encoder.encode(data);// 返回Base64编码过的字节数组字符串
		  }
	 /**
	  * 对字节数组字符串进行Base64解码并生成图片
	  * @param imgBase64
	  * @param imgFilePath
	  * @return
	  */
	 public static boolean generateImage(String imgBase64,String imgFilePath){
		 if(imgBase64 == null){//图像数据为空
			 return false;
		 }
		 try {
			byte [] b = Base64.decodeBase64(imgBase64);
			for(int i=0;i<b.length;i++){
				if(b[i]<0){
					//调整异常数据
					b[i] += 256;
				}
			}
			
			OutputStream outputStream = new FileOutputStream(imgFilePath);
			BufferedOutputStream bOutputStream = new BufferedOutputStream(outputStream);
			bOutputStream.write(b, 0, b.length);
			bOutputStream.flush();
			bOutputStream.close();
			
			
			/*File file = new File(imgFilePath);
			
			File file2File = new File("C:/Users/Administrator/Desktop/test.txt");
			Writer  out =new FileWriter(file2File);
			String  str1 ="这是没有转化的"+b.length;
			String str2 = "这是处理过的"+file.length();
			out.write(str1+str2);
			out.close();*/
			return true;
		} catch (Exception e) {
			return false;
		}
	 }
	 public static String base64Str(){
		 String imgFilePathString="D:\\java\\content\\eclipse-win64\\hj_zhida_api\\src\\main\\webapp\\img\\zhangsijun.jpg";
		 return getImageStr(imgFilePathString);
	 }
}
